import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/auth_provider.dart';
import '../screens/login_screen.dart';
import '../screens/splash_screen.dart';

/// 认证守卫Widget - 用于保护需要登录才能访问的页面
class AuthGuard extends StatelessWidget {
  final Widget child;
  final bool requireAuth;

  const AuthGuard({
    super.key,
    required this.child,
    this.requireAuth = true,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<AuthProvider>(
      builder: (context, authProvider, _) {
        // 如果不需要认证，直接显示子组件
        if (!requireAuth) {
          return child;
        }

        // 根据认证状态决定显示什么
        switch (authProvider.state) {
          case AuthState.initial:
          case AuthState.loading:
            // 正在加载，显示启动屏幕
            return const SplashScreen();
            
          case AuthState.authenticated:
            // 已认证，显示目标页面
            return child;
            
          case AuthState.unauthenticated:
          case AuthState.error:
            // 未认证或错误，显示登录页面
            return const LoginScreen();
        }
      },
    );
  }
}

/// 路由守卫 - 用于控制路由跳转
class RouteGuard {
  /// 检查是否可以访问受保护的路由
  static bool canAccess(BuildContext context) {
    final authProvider = context.read<AuthProvider>();
    return authProvider.isAuthenticated;
  }

  /// 导航到受保护的页面
  static Future<void> navigateToProtected(
    BuildContext context,
    Widget page, {
    bool replace = false,
  }) async {
    if (canAccess(context)) {
      if (replace) {
        await Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => page),
        );
      } else {
        await Navigator.of(context).push(
          MaterialPageRoute(builder: (context) => page),
        );
      }
    } else {
      // 未登录，跳转到登录页面
      await Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (context) => const LoginScreen()),
      );
    }
  }

  /// 登录成功后的导航处理
  static Future<void> handleLoginSuccess(BuildContext context) async {
    // 等待一下确保状态更新完成
    await Future.delayed(const Duration(milliseconds: 100));
    
    if (context.mounted) {
      // 导航到主页面，清除所有之前的路由
      await Navigator.of(context).pushNamedAndRemoveUntil(
        '/',
        (route) => false,
      );
    }
  }

  /// 登出处理
  static Future<void> handleLogout(BuildContext context) async {
    final authProvider = context.read<AuthProvider>();
    await authProvider.logout();
    
    if (context.mounted) {
      // 导航到登录页面，清除所有之前的路由
      await Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => const LoginScreen()),
        (route) => false,
      );
    }
  }

  /// Token过期处理
  static Future<void> handleTokenExpired(BuildContext context) async {
    final authProvider = context.read<AuthProvider>();
    
    // 尝试刷新Token
    final refreshed = await authProvider.refreshToken();
    
    if (!refreshed && context.mounted) {
      // 刷新失败，登出并跳转到登录页面
      await handleLogout(context);
      
      // 显示提示信息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: const Text('登录已过期，请重新登录'),
          backgroundColor: Colors.orange.shade600,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
        ),
      );
    }
  }
}

/// AuthGuard的静态方法，用于在需要的地方快速包装Widget
class Auth {
  /// 包装需要认证的Widget
  static Widget guard(Widget child, {bool requireAuth = true}) {
    return AuthGuard(
      requireAuth: requireAuth,
      child: child,
    );
  }

  /// 创建受保护的路由
  static Route<T> protectedRoute<T extends Object?>(
    Widget Function(BuildContext) builder,
    RouteSettings settings,
  ) {
    return MaterialPageRoute<T>(
      settings: settings,
      builder: (context) => AuthGuard(
        child: Builder(builder: builder),
      ),
    );
  }
}